package com.hx.vending.controller;

import com.alibaba.fastjson.JSON;
import com.hx.vending.bean.entity.TicketSign;
import com.hx.vending.pay.SignUtils;
import com.hx.vending.pay.WXPayUtil;
import com.hx.vending.util.Constant;
import com.hx.vending.util.Msg;
import com.hx.vending.util.ToolUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2018/12/3.
 */
@Controller
public class BuyerController {
    // 获取logger实例
    protected static Logger logger = Logger.getLogger(BuyerController.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/wxconfig")
    @ResponseBody
    public Msg buyerReceiveMoney(HttpServletRequest request){
        String reqUrl = request.getParameter("url");
        System.out.println(reqUrl);
        logger.info("开始调用公众号微信扫一扫");
        TicketSign ticketSign = new TicketSign();
        ticketSign.setUrl(reqUrl);
        ticketSign.setTimestamp(SignUtils.create_timestamp());
        ticketSign.setNoncestr(SignUtils.create_nonce_str());
        ticketSign.setAppId(Constant.APPID);
        try {
            System.out.println("---------------获取token前----------------");
            //获取token之前
            String token = (String) redisTemplate.opsForValue().get("token");
            System.out.println("先获取reids的token:" + token);
            if (ToolUtil.isEmpty(token)) {
                //获取企业微信号的token值
                String getToken = WXPayUtil.getToken();
                System.out.println("微信调用的token:" + getToken);
                redisTemplate.opsForValue().set("token", getToken, 3600, TimeUnit.SECONDS);
                token = (String) redisTemplate.opsForValue().get("token");
                System.out.println("调用后赋值给redis的token:" + token);
            }
            System.out.println("调用微信扫一扫的token:" + token);
            //token
            ticketSign.setTicket(WXPayUtil.getTicket(token));
            ticketSign.setSignature(WXPayUtil.jssdkSignature(ticketSign.getTicket(), ticketSign.getTimestamp(),
                    ticketSign.getNoncestr(), reqUrl));
        }catch (Exception e){
            Msg.fail().add("va_msg", "服务器正在维护");
        }
        Msg msg = Msg.success();
        msg.add("appId", Constant.APPID);
        msg.add("timestamp", ticketSign.getTimestamp());
        msg.add("nonceStr", ticketSign.getNoncestr());
        msg.add("ticket",ticketSign.getTicket());
        msg.add("signature", ticketSign.getSignature());
        msg.add("url", ticketSign.getUrl());// 把新数据加上
        return msg;
    }

    /**
     * 交易异步通知-- 没测试 交易异步通知 推送规则：银行收到微信、支付宝通知则实时通知，会实时通知给代理商，若首次通知失败，
     * 后面会继续推送5次，第2.3会继续实时推送，第4次隔10分钟，第5隔三十分钟，第6次隔一小时。
     *
     * @return
     */
    @RequestMapping(value = {"/asynchronous"})
    public void metispayNotify(HttpServletRequest request, HttpServletResponse response, HttpSession session)throws Exception{
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-type", "text/html;charset=UTF-8");

        String body = "";

        ServletInputStream inputStream = request.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        while (true) {
            String info = br.readLine();
            if (info == null) {
                break;
            }
            if (body == null || "".equals(body)) {
                body = info;
            } else {
                body += info;
            }
        }

    }
}
